package com.example.demo.util;

import com.example.demo.entity.User;
import org.apache.poi.ss.usermodel.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.ArrayList;
import java.util.List;

public class ExcelUtil {
    public static List<User> parseExcel(MultipartFile file) {
        List<User> users = new ArrayList<>();
        try {
            Workbook workbook = WorkbookFactory.create(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(0);
            
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) continue;
                
                User user = new User();
                user.setName(getCellValueAsString(row.getCell(0)));
                user.setEmail(getCellValueAsString(row.getCell(1)));
                user.setPhone(getCellValueAsString(row.getCell(2)));
                user.setAddress(getCellValueAsString(row.getCell(3)));
                
                users.add(user);
            }
            
            workbook.close();
        } catch (Exception e) {
            throw new RuntimeException("解析Excel文件失败", e);
        }
        return users;
    }
    
    private static String getCellValueAsString(Cell cell) {
        if (cell == null) return "";
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                return String.valueOf((long) cell.getNumericCellValue());
            default:
                return "";
        }
    }
} 